package com.gti.mobilsafe;

import java.util.List;

import com.gti.mobilsafe.pojos.ContactInfo;
import com.gti.mobilsafe.utils.ContactInfoProvider;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class SelectContractActivity extends Activity {

	private ListView listView;
	private LinearLayout ll_select_loading;
	private List<ContactInfo> infos;
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message message){
			super.handleMessage(message);
			ll_select_loading.setVisibility(View.INVISIBLE);
			listView.setAdapter(new ContactAdapt());
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_contract);
		listView = (ListView) findViewById(R.id.lv_select_contract);
		ll_select_loading = (LinearLayout) findViewById(R.id.ll_select_loading);
		ll_select_loading.setVisibility(View.VISIBLE);
		
		new Thread(){
			public void run(){
				infos = ContactInfoProvider.getContactInfos(getApplicationContext());
				
				handler.sendEmptyMessage(0);
	
				
				
			}
		}.start();
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ContactInfo contactInfo = (ContactInfo) listView.getItemAtPosition(position);
				Intent intent = new Intent();
				intent.putExtra("phone", contactInfo.getPhone());
				setResult(0,intent);
				finish();
			}
			
		});
	}

	private class ContactAdapt extends BaseAdapter{

		@Override
		public int getCount() {
			
			return infos.size();
		}

		@Override
		public Object getItem(int position) {
			
			return infos.get(position);
		}

		@Override
		public long getItemId(int position) {
			
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			View view = View.inflate(SelectContractActivity.this, R.layout.contract_item, null);
			TextView nameTextView  = (TextView) view.findViewById(R.id.contact_item_name_tv);
			TextView phoneTextView = (TextView) view.findViewById(R.id.contact_item_phone_tv);
			ContactInfo contactInfo = infos.get(position);
			nameTextView.setText(contactInfo.getName());
			phoneTextView.setText(contactInfo.getPhone());
			
			return view;
		}
	}
	
}
